package com.lx.core.weight.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lx.core.util.DateUtils;
import com.lx.core.weight.entity.Weight;
import com.lx.core.weight.entity.dto.EmployerStaticDTO;
import com.lx.core.weight.entity.dto.WeightPageDTO;
import com.lx.core.weight.entity.vo.*;
import com.lx.core.weight.mapper.WeightMapper;
import com.lx.core.weight.service.WeightService;
import com.lx.framework.core.entity.SysAdmin;
import com.lx.framework.core.model.SysAdminDTO;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lx
 * @date 2025/08/26 09:22
 **/
@Service
public class WeightServiceImpl extends ServiceImpl<WeightMapper, Weight> implements WeightService {

    private final WeightMapper weightMapper;

    public WeightServiceImpl(WeightMapper weightMapper) {
        this.weightMapper = weightMapper;
    }

    @Override
    public WeightVO page(IPage<WeightVO> page, WeightPageDTO weightPageDTO) {
        weightPageDTO.setStartTime(DateUtils.formatStartTime(weightPageDTO.getStartTime()));
        weightPageDTO.setEndTime(DateUtils.formatEndTime(weightPageDTO.getEndTime()));
        IPage<WeightPageList> pageList = weightMapper.findWeightPage(page, weightPageDTO);
        WeightVO result = new WeightVO();
        FeeTotalVO feeTotalVO = weightMapper.getTotalByQuery(weightPageDTO);
        if(!ObjectUtil.isEmpty(feeTotalVO))
        {
            result.setAllTotal(feeTotalVO.getAllTotal());
            result.setAllWeightFee(feeTotalVO.getAllWeightFee());
        }
//        // 计算业务统计值
//        int allTotal = 0;
//        int allWeightFee = 0;
//        if (!ObjectUtil.isEmpty(pageList) && !ObjectUtil.isEmpty(pageList.getRecords())) {
//            for (WeightPageList record : pageList.getRecords()) {
//                allTotal += record.getTotal();
//                allWeightFee += record.getWeightFee();
//            }
//        }
//        // 构建返回结果
        result.setRecords(pageList.getRecords());
        result.setTotal(pageList.getTotal());
        result.setSize(pageList.getSize());
        result.setCurrent(pageList.getCurrent());
        result.setPages(pageList.getPages());

        return result;
    }

    @Override
    public List<WeightPageList> exportExcel(WeightPageDTO weightPageDTO) {
        weightPageDTO.setStartTime(DateUtils.formatStartTime(weightPageDTO.getStartTime()));
        weightPageDTO.setEndTime(DateUtils.formatEndTime(weightPageDTO.getEndTime()));
        return weightMapper.exportExcel(weightPageDTO);
    }

    @Override
    public CurrentDayDataVO getCurrentDayData() {
        CurrentDayDataVO currentDayDataVO = new CurrentDayDataVO();
        QueryWrapper<Weight> queryWrapper = new QueryWrapper();
        queryWrapper.ge("gross_create_time", LocalDate.now().atStartOfDay())
                .le("gross_create_time", LocalDate.now().atTime(23, 59, 59));
        List<Weight> weightList = weightMapper.selectList(queryWrapper);
        if (!ObjectUtil.isEmpty(weightList)) {
            currentDayDataVO.setCarNumber(weightList.size());
            int allTotal = 0;
            int allWeightFee = 0;
            int allNetWeight = 0;
            for (Weight weight : weightList) {
                if (!ObjectUtil.isEmpty(weight.getWeightFee()) && weight.getWeightFee() > 0) {
                    allWeightFee += weight.getWeightFee();
                }
                if (!ObjectUtil.isEmpty(weight.getTotal()) && weight.getTotal() > 0) {
                    allTotal += weight.getTotal();
                }
                if (!ObjectUtil.isEmpty(weight.getNet()) && weight.getNet() > 0) {
                    allNetWeight += weight.getNet();
                }
            }
            currentDayDataVO.setAllNetWeight(allNetWeight);
            currentDayDataVO.setAllTotal(allTotal);
            currentDayDataVO.setAllWeightFee(allWeightFee);
        }
        QueryWrapper<Weight> yesterdayWrapper = new QueryWrapper();
        LocalDate yesterday = LocalDate.now().minusDays(1);
        yesterdayWrapper.ge("gross_create_time", yesterday.atStartOfDay())
                .le("gross_create_time", yesterday.atTime(23, 59, 59));
        List<Weight> yesterdayWeightList = weightMapper.selectList(yesterdayWrapper);
        if (!ObjectUtil.isEmpty(yesterdayWeightList)) {
            currentDayDataVO.setYesterdayCarNumber(yesterdayWeightList.size());
            int yesterdayAllTotal = 0;
            int yesterdayAllWeightFee = 0;
            int yesterdayAllNetWeight = 0;
            for (Weight weight : yesterdayWeightList) {
                if (!ObjectUtil.isEmpty(weight.getWeightFee()) && weight.getWeightFee() > 0) {
                    yesterdayAllWeightFee += weight.getWeightFee();
                }
                if (!ObjectUtil.isEmpty(weight.getTotal()) && weight.getTotal() > 0) {
                    yesterdayAllTotal += weight.getTotal();
                }
                if (!ObjectUtil.isEmpty(weight.getNet()) && weight.getNet() > 0) {
                    yesterdayAllNetWeight += weight.getNet();
                }
            }
            currentDayDataVO.setYesterdayAllNetWeight(yesterdayAllNetWeight);
            currentDayDataVO.setYesterdayAllTotal(yesterdayAllTotal);
            currentDayDataVO.setYesterdayAllWeightFee(yesterdayAllWeightFee);
        }
        return currentDayDataVO;
    }

    @Override
    public List<CurrentDayGoodsWeightVO> getCurrentDayGoodsWeight() {
        return weightMapper.getCurrentDayGoodsWeight();
    }

    @Override
    public List<PriceLastSevenGoodsVO> getLastSevenDayAveragePrice(int goodsType) {
        if (goodsType < 0) {
            List<PriceLastSevenGoodsVO> allRecords = weightMapper.getLastSevenDayAveragePrice(goodsType);
            List<PriceLastSevenGoodsVO> filteredByName = allRecords.stream()
                    .filter(record -> record.getGoodsName() != null && !record.getGoodsName().trim().isEmpty())
                    .collect(Collectors.toList());
            Set<String> validNames = filteredByName.stream()
                    .collect(Collectors.groupingBy(PriceLastSevenGoodsVO::getGoodsName))
                    .entrySet().stream()
                    .filter(e -> e.getValue().stream().anyMatch(r -> r.getGoodsPrice() != null && r.getGoodsPrice().compareTo(BigDecimal.ZERO) > 0))
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toSet());

            // === 第三步：只保留“有效蔬菜”的所有记录 ===
            List<PriceLastSevenGoodsVO> result = filteredByName.stream()
                    .filter(r -> validNames.contains(r.getGoodsName()))
                    .collect(Collectors.toList());
            return result;
        }else{
            return weightMapper.getLastSevenDayAveragePrice(goodsType);
        }
    }

    @Override
    public List<PriceLastFiveYearGoodsVO> getPastFiveYearGoodsTypePriceByWeek(int goodsType) {
        return weightMapper.getPastFiveYearGoodsTypePriceByWeek(goodsType);
    }

    @Override
    public List<WeightLastFiveYearGoodsVO> getPastFiveYearGoodsTypeWeightByWeek(int goodsType) {
        return weightMapper.getPastFiveYearGoodsTypeWeightByWeek(goodsType);
    }

    @Override
    public List<PriceLastFiveYearGoodsVO> getPastFiveYearGoodsTypePriceByMonth(int goodsType) {
        return weightMapper.getPastFiveYearGoodsTypePriceByMonth(goodsType);
    }

    @Override
    public List<WeightLastFiveYearGoodsVO> getPastFiveYearGoodsTypeWeightByMonth(int goodsType) {
        return weightMapper.getPastFiveYearGoodsTypeWeightByMonth(goodsType);
    }

    @Override
    public List<PriceLastFiveYearGoodsVO> getPastFiveYearGoodsTypePriceByDay(int goodsType) {
        return weightMapper.getPastFiveYearGoodsTypePriceByDay(goodsType);
    }

    @Override
    public List<WeightLastFiveYearGoodsVO> getPastFiveYearGoodsTypeWeightByDay(int goodsType) {
        return weightMapper.getPastFiveYearGoodsTypeWeightByDay(goodsType);
    }

    @Override
    public List<FeeLastMonthVO> getLastMonthDayFee(int goodsType) {
        return weightMapper.getLastMonthDayFee(goodsType);
    }

    @Override
    public List<WeightNumberUseInfoVO> getCurrentWeightNumberUse(int goodsType) {
        return weightMapper.getCurrentWeightNumberUse(goodsType);
    }

    @Override
    public Page<SysAdminDTO> getSyaAdminPage(IPage<SysAdminDTO> page, String username) {
        return weightMapper.getSyaAdminPage(page, username);
    }

    @Override
    public EmployerWeightCountVO getEmployerWeightCount(IPage<EmployerWeightCountVO> page,EmployerStaticDTO employerStaticDTO) {

        IPage<EmployerWeightCountList> pageList = weightMapper.getEmployerWeightCount(page, employerStaticDTO);
        // 构建返回结果
        EmployerWeightCountVO result = new EmployerWeightCountVO();
        result.setRecords(pageList.getRecords());
        result.setTotal(pageList.getTotal());
        result.setSize(pageList.getSize());
        result.setCurrent(pageList.getCurrent());
        result.setPages(pageList.getPages());
        return result;
    }
}
